package com.lagou.rabbitmq.topic;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Random;
import java.util.concurrent.TimeoutException;

public class Producer {

    private static final String[] LOG_LEVEL = {"info","error","warn"};
    private static final String[] LOG_AREA = {"beijing","shanghai","shenzhen"};
    private static final String[] LOG_BIZ = {"edu-online","biz-online","emp-online"};

    private static final Random random = new Random();

    public static void main(String[] args) throws IOException, TimeoutException {
        //获取连接工厂
        ConnectionFactory factory = new ConnectionFactory();
        //设置主机名 hostname
        factory.setHost("47.115.74.219");
        //设置虚拟主机名称 /在url中的转义字符 %2f
        factory.setVirtualHost("/");
        //用户名
        factory.setUsername("root");
        //密码
        factory.setPassword("123456");
        //amqp的端口号
        factory.setPort(5672);

        //建立TCP连接
        Connection connection = factory.newConnection();
        //获取通道
        Channel channel = connection.createChannel();

        //声明交换器
        //第一个参数 交换器名称
        //第二个参数 交换器类型
        //第三个参数 是否持久化
        //第四个参数 是否自动删除
        //第五个参数 交换器属性信息
        channel.exchangeDeclare("ex.topic", BuiltinExchangeType.TOPIC,true,false,null);


        //发送消息
        //交换器的名称
        //该消息的路由键
        //该消息的属性
        //消息内容的字节数组
        String routingKey,message,area,level,biz;
        for(int i = 0;i <= 15;i++) {
            area = LOG_AREA[random.nextInt(LOG_AREA.length)];
            level = LOG_LEVEL[random.nextInt(LOG_LEVEL.length)];
            biz = LOG_BIZ[random.nextInt(LOG_BIZ.length)];
            routingKey = area + "." + biz + "." + level;
            message = "LOG:[" + level + "]:这是[" + area + "]地区[" + biz + "]服务器发来的消息";
            channel.basicPublish("ex.topic", routingKey, null, message.getBytes(StandardCharsets.UTF_8));
        }
        //关闭通道
        channel.close();
        //关闭连接
        connection.close();
    }

}
